package org.zht.dormpro.auth.controller;

import com.xiaoleilu.hutool.util.CollectionUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zht.dormpro.auth.bean.AuthUser;
import org.zht.dormpro.auth.bean.LoginBean;
import org.zht.dormpro.auth.bean.Tree;
import org.zht.dormpro.pub.constant.Enums;
import org.zht.dormpro.auth.model.SysPermission;
import org.zht.dormpro.auth.service.ISysUserService;
import org.zht.dormpro.pub.ResponseMap;
import org.zht.dormpro.pub.util.ShiroUtil;

import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private ISysUserService sysUserService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public ResponseMap login(LoginBean loginBean){
        Subject subject = ShiroUtil.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginBean.getUsername(),loginBean.getPassword());
        try {
            subject.login(usernamePasswordToken);
            return ResponseMap.success(Enums.LoginStatus.LOGIN_SUCCESS.getDesc());
        } catch (AuthenticationException e) {
            if(e instanceof IncorrectCredentialsException){
                return ResponseMap.error(Enums.LoginStatus.LOGIN_FAILER.getDesc());
            }
            return ResponseMap.error(e.getMessage());
        }
    }
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(){
        return "login";
    }

    @RequestMapping(value = "/main",method = RequestMethod.GET)
    public String mainPage(Model model){
        AuthUser authUser = ShiroUtil.getAuthUser();
        List<Tree<SysPermission>> userMenuTree = sysUserService.getUserMenuTree(authUser.getUserId());
        model.addAttribute("authUser",authUser);
        model.addAttribute("userMenuTree",userMenuTree);
        if(CollectionUtil.isEmpty(userMenuTree)){
            model.addAttribute("notHasPermission","notHasPermission");
            //test
        }
        return "main/index_admin";
    }

    @RequestMapping(value = "/403")
    public String notPermission(){
        return "403";
    }
}
